import { Coord } from "./Coord";

/** 获取两个点之间的连线的点位数组的函数 */
export function GetLine(from: Coord, to: Coord): Coord[] {
    let line: Coord[] = [];

    let x = from.tileX;
    let y = from.tileY;
    let dx = to.tileX - from.tileX;
    let dy = to.tileY - from.tileY;

    let inverted = false;
    let step = Math.sign(dx);
    let gradientStep = Math.sign(dy);

    let longest = Math.abs(dx);
    let shortest = Math.abs(dy);

    if (longest < shortest) {
        inverted = true;

        step = Math.sign(dy);
        gradientStep = Math.sign(dx);

        longest = Math.abs(dy);
        shortest = Math.abs(dx);
    }

    let gradientAccumulation = longest / 2;
    for (let i = 0; i < longest; i++) {
        line.push(new Coord(x, y));
        if (inverted) {
            y += step;
        } else {
            x += step;
        }
        gradientAccumulation += shortest;
        if (gradientAccumulation >= longest) {
            if (inverted) {
                x += gradientStep;
            } else {
                y += gradientStep;
            }

            gradientAccumulation -= longest;
        }
    }
    return line;
}
